<?php
declare (strict_types=1);

namespace app\index\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Transfer as TransferModel;
use think\exception\ValidateException;

class Transfer extends Base
{
    public function index()
    {
        return View::fetch();
    }

    public function record()
    {
        return View::fetch();
    }

    public function getList(): Json
    {
        $param = $this->request->param();
        $map = ['uid|take_uid' => $this->user->id];
        $list = TransferModel::getPageList($map, '*', $param['page'], 20, false, ['take', 'user']);
        foreach ($list['data'] as &$v) {
            if ($v->uid == $this->user->id) {
                $v->trStatus = '转出';
                $v->trUser = $v->take->code . '【' . $v->take->nickname . '】';
            } else {
                $v->trStatus = '转入';
                $v->trUser = $v->user->code . '【' . $v->user->nickname . '】';
            }
        }

        return json($list);
    }

    public function verify(): Json
    {
        $code = $this->request->param('code');
        $nickname = \app\common\model\User::where(['mobile' => $code, 'is_del' => 0])->value('nickname');
        if ($nickname) {
            return json(['code' => 1, 'result' => $nickname]);
        } else {
            return json(['code' => -1, 'result' => '会员不存在']);
        }
    }

    public function save(): Json
    {
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Transfer');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }

        return json(TransferModel::add($param, $this->user, $this->system));
    }
}